package com.test.sdk.sender.service;

import com.test.sdk.common.util.HTTPUtil;
import com.test.sdk.sender.dao.SenderDAO;
import com.test.sdk.sender.pojo.SenderQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.List;

@Component
public class SenderThread implements Runnable {
    protected boolean start = false;

    @PostConstruct
    public void init() {
        this.start=true;
        new Thread(this).start();
    }

    @Autowired
    private SenderDAO senderDAO;

    @Override
    public void run() {
        try {
            while (this.start) {
                System.out.println("更新发");
                List<SenderQueue> queues = senderDAO.getQueue();
                for (SenderQueue queue : queues) {
                    if(queue.getNoticeTimes()>=10){//10次通知都没成功
                        senderDAO.addBadQueue(queue);
                        senderDAO.deleteQueue(queue.getId());
                        continue;
                    }
                    String res= HTTPUtil.httpPost(queue.getNoticeUrl(),queue.getParam(),"utf-8");
                    if("ok".equals(res)){//发成功了
                        senderDAO.deleteQueue(queue.getId());
                    }else{
                        senderDAO.updateTime(queue.getId());
                    }
                }
                Thread.sleep(5000);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @PreDestroy
    public void stop() {
        this.start = false;
    }

}
